package com.gitee.wsl.doc.prosemirror.model.node.ext

import com.gitee.wsl.doc.prosemirror.model.node.Node
import com.gitee.wsl.doc.prosemirror.model.node.NodeType


// Try to find a point where a node of the given type can be inserted near `pos`, by searching up
// the node hierarchy when `pos` itself isn't a valid place but is at the start or end of a node.
// Return null if no position was found.
fun Node.insertPoint(pos: Int, nodeType: NodeType): Int? {
    val doc = this
    val thisPos = doc.resolve(pos)
    if (thisPos.parent.canReplaceWith(thisPos.index(), thisPos.index(), nodeType)) return pos

    if (thisPos.parentOffset == 0) {
        for (d in thisPos.depth - 1 downTo 0) {
            val index = thisPos.index(d)
            if (thisPos.node(d).canReplaceWith(index, index, nodeType)) return thisPos.before(d + 1)
            if (index > 0) return null
        }
    }
    if (thisPos.parentOffset == thisPos.parent.content.size) {
        for (d in thisPos.depth - 1 downTo 0) {
            val index = thisPos.indexAfter(d)
            if (thisPos.node(d).canReplaceWith(index, index, nodeType)) return thisPos.after(d + 1)
            if (index < thisPos.node(d).childCount) return null
        }
    }
    return null
}